/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cydonia.daemon;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.cydonia.config.Configuration;
import org.cydonia.engines.interfaces.Engine;
import org.cydonia.ip.ExternalIp;
import org.cydonia.ip.interfaces.CaptureIp;
import org.cydonia.misc.FileUtil;

/**
 *
 * @author franklin
 */
public class TimerTask extends java.util.TimerTask {

    Configuration c;

    public TimerTask(Configuration c) {
        this.c = c;
    }

    @Override
    public void run() {
        try {
            String username = c.getValue(Configuration.USERNAME);
            String password = c.getValue(Configuration.PASSWORD);
            String domain = c.getValue(Configuration.DOMAIN);
            String engine = c.getValue(Configuration.ENGINE);

            CaptureIp ci = new ExternalIp();
            String ip = ci.getIpAddress();

            Class classeEngine = Class.forName("org.cydonia.engines." + engine);
            Engine e = (Engine) classeEngine.newInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dt = new Date();

            String pathFileForOldIp = "/tmp/cydonia-oldIp";

            List<String> l = FileUtil.readTextLines(pathFileForOldIp, true);
            String oldIp = "";
            if (!l.isEmpty()) {
                oldIp = l.get(0);
            }

            if (!oldIp.trim().equals(ip.trim())) {
                String engineMessage = e.doUpdate(username, password, domain, ip);
                System.out.println(sdf.format(dt) + ": " + engineMessage);
                if (engineMessage.contains("success")) {
                    FileUtil.saveStringOnFile(pathFileForOldIp, ip);
                }
            } else {
                System.out.println("Update unnecessary, IP has not changed.");
            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(TimerTask.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TimerTask.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(TimerTask.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(TimerTask.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(TimerTask.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}
